#pragma once
#include <string>
#include <cassert>
#include <fstream>
#include <memory>

#include <jsoncpp/json/json.h>
#include "oj_model.hpp"
#include "oj_view.hpp"
#include "../comm/util.hpp"
#include "../comm/log.hpp"
#include "../comm/httplib.h"

namespace ns_control
{
    using namespace ns_model;
    using namespace ns_util;
    using namespace ns_log;
    using namespace ns_view;
    using namespace httplib;

    class Machine
    {
    public:
        Machine() : _ip("0.0.0.0"), _port(0), _load(0), _mtx(nullptr)
        {
        }
        ~Machine() {}

    public:
        // 提升主机负载
        void IncLoad()
        {
            if (_mtx)  _mtx->lock();
            ++_load;
            if (_mtx) _mtx->unlock();
        }
        // 减少主机负载
        void DecLoad()
        {
            if (_mtx) _mtx->lock();
            --_load;
            if (_mtx) _mtx->unlock();
        }
        void ResetLoad()
        {
            if (_mtx) _mtx->lock();
            _load = 0;
            if (_mtx)  _mtx->unlock();
        }

        // 获取主机负载, 统一接口
        uint64_t Load()
        {
            uint64_t load = 0;
            if (_mtx) _mtx->lock();
            load = _load;
            if (_mtx) _mtx->unlock();
            return load;
        }

    public:
        std::string _ip;
        uint16_t _port;
        uint64_t _load;   // 主机负载
        std::mutex *_mtx; // C++11 锁是不允许拷贝的
    };

    const std::string machine_conf = "./conf/server_machine.conf";

    class LoadBlance
    {
    public:
        LoadBlance()
        {
            assert(LoadConf(machine_conf));
            LOG(Loglevel::INFO) << "加载" << machine_conf << "成功...\n";
        }
        ~LoadBlance() {}

        bool SmartChoice(int *id, Machine **mach)
        {
            // 负载均衡的算法
            // 1. 随机数+hash
            // 2. 轮询+hash

            _mtx.lock();
            if (_online.size() == 0)
            {
                _mtx.unlock();
                LOG(Loglevel::FATAL) << "所有编译服务主机已全部离线, 请运维的老铁赶紧上线服务!\n";
                return false;
            }

            *id = _online[0], *mach = &_machines[_online[0]];
            uint64_t minload = _machines[_online[0]].Load();
            for (int i = 1; i < _online.size(); i++)
            {
                uint64_t curload = _machines[_online[i]].Load();
                if (curload < minload)
                {
                    minload = curload;
                    *id = _online[i];
                    *mach = &_machines[_online[i]];
                }
            }
            _mtx.unlock();
            return true;
        }

        void OfflineMachine(int which)
        {
            _mtx.lock();
            for (auto iter = _online.begin(); iter < _online.end(); iter++)
            {
                if (*iter == which)
                {
                    _machines[*iter].ResetLoad();
                    _offline.push_back(which);
                    _online.erase(iter);
                    break;
                }
            }
            _mtx.unlock();
            LOG(Loglevel::INFO) << "主机" << which << "离线" << std::endl;
        }

        // 统一上限
        void OnlineMachine()
        {
            _mtx.lock();
            _online.insert(_online.end(), _offline.begin(), _offline.end());
            _offline.erase(_offline.begin(), _offline.end());
            _mtx.unlock();
            LOG(Loglevel::INFO) << "所有主机已全部上线\n";
        }

        void ShowMachines() // DEBUG
        {
            _mtx.lock();  
            std::cout << "当前所有在线主机: ";
            for(auto num : _online)
            {
                std::cout << num << " ";
            }
            std::cout << std::endl;

            std::cout << "当前离线主机: ";
            for(auto num : _offline)
            {
                std::cout << num << " ";
            }
            std::cout << std::endl;
            _mtx.unlock();
        }
    private:
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream ifs(machine_conf);
            if (!ifs.is_open())
            {
                return false;
            }

            std::string line;
            while (std::getline(ifs, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    continue;
                }

                Machine mach;
                mach._ip = tokens[0];
                mach._port = atoi(tokens[1].c_str());
                mach._load = 0;
                mach._mtx = new std::mutex();
                _online.push_back(_machines.size());
                _machines.push_back(mach);
            }

            ifs.close();
            return true;
        }
    private:
        std::vector<Machine> _machines;
        std::vector<int> _online;  // 在线主机下标
        std::vector<int> _offline; // 离线主机下标
        std::mutex _mtx;
    };

    class Control
    {
    public:
        // 根据题目数据构建网页
        //  html: 输出型参数
        bool AllQuestions(std::string *html)
        {
            bool ret = true;
            std::vector<struct Question> all;
            if (_model.GetAllQuestions(&all))
            {
                sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2){
                    return atoi(q1._number.c_str()) < atoi(q2._number.c_str());
                });
                // 获取题目列表成功，构建网页html
                _view.AllExpandHtml(all, html);   
            }
            else
            {
                ret = false;
                *html = "获取题目失败, 形成题目列表失败";
            }
            return ret;
        }

        bool Question(std::string &number, std::string *html)
        {
            bool ret = true;
            struct Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                _view.OneExpandHtml(q, html);
            }
            else
            {
                ret = false;
                *html = "指定题目: " + number + " 不存在!";
            }
            return ret;
        }

        void Judge(const std::string &number, const std::string& in_json, std::string *out_json)
        {
            // 1. 获取题目细节
            struct Question q;
            _model.GetOneQuestion(number, &q);

            // 2. in_json反序列化，等到对应的input、prev_code(和测试用例进行拼接)
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string prev_code = in_value["code"].asString();
            std::string input = in_value["input"].asString();

            // 3. 填充编译运行json所需的相关数据（用户提交代码和测试用例进行拼接）
            Json::Value compile_value;
            compile_value["input"] = input;
            compile_value["code"] = prev_code + "\n" + q._tail;
            compile_value["cpu_limit"] = q._cpu_limit;
            compile_value["mem_limit"] = q._mem_limit;
            Json::FastWriter writer;
            std::string compile_json = writer.write(compile_value);
            
            // 4. 选择负载最小的主机
             // 规则: 一直选择，直到主机可用，否则，就是全部挂掉
            while(true)
            {
                int id = -1;
                Machine *mach = nullptr;
                if(!_load_blance.SmartChoice(&id, &mach)) // 选择失败，意味着所有主机已离线
                    break;

                // 5. 发起http请求，得到结果
                Client cli(mach->_ip, mach->_port);
                mach->IncLoad();
                LOG(Loglevel::INFO) << "选择主机成功， 主机id: " << id << " 详情 " << mach->_ip << ":" << mach->_port \
                                    << " 当前主机的负载: " << mach->_load << std::endl;
                if(auto res = cli.Post("/compile_and_run", compile_json, "application/json;charset=utf-8"))
                {
                    if(res->status == 200)
                    {
                        *out_json = res->body;
                        mach->DecLoad();
                        LOG(Loglevel::INFO) << "编译运行成功...\n";
                        break;
                    }
                }
                else    
                {   
                    // 请求失败
                    LOG(Loglevel::ERROR) << "当前请求的主机, id:" << id << " 详情 " << mach->_ip << ":" << mach->_port \
                                         << "可能已经离线\n";
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachines(); //调试
                }
            }
        }
    private:
        LoadBlance _load_blance;    // 核心负载均衡控制器
        Model _model;               // 用于获取后台数据
        View _view;                 // 提高html渲染功能
    };
}